package threadtest;

import java.util.concurrent.*;

public class FutureTaskExample {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        // 创建一个Callable任务
        Runnable callable = () -> {
            try {
                Thread.sleep(2000); // 模拟耗时操作
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        };

        // 创建FutureTask，传入Callable任务和结果值
        FutureTask<Integer> futureTask = new FutureTask<>(callable, 123);

        // 创建线程来执行FutureTask
        Thread thread = new Thread(futureTask);
        thread.start();

        // 等待任务执行完成并获取结果
        try {
            Integer result = futureTask.get(); // 这里会阻塞直到任务完成
            System.out.println("Task result: " + result); // 123
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}
